import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'

import { useLoadingBarStore } from '@/store/modules/eventBus'
// import { useMenuStore } from '@/store/modules/menu'

import eventBus from '@/layout/eventBus.vue'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: eventBus,
    name: 'main',
    redirect: '/main',
    children: [
      {
        path: '/login',
        meta: {
          title: '登录',
        },
        component: () => import('@/layout/login.vue'),
      },
      {
        path: '/:catchAll(.*)',
        meta: {
          title: '页面不存在',
        },
        component: () => import('@/layout/404.vue'),
      },
      {
        path: '/main',
        meta: {
          title: '主页面',
        },
        component: () => import('@/views/main.vue'),
      },
    ],
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 路由守卫
router.beforeEach((to, _from, next) => {
//   const { loadingBarShow } = storeToRefs(useLoadingBarStore())
//   const { setMenuList, menuList, fistMenu } = useMenuStore()

//   // 目前对于路由的处理方式是将所有动态路由均放置在layout路由下
//   const routes = router.getRoutes()
//   const isInitRoutes = !routes.some((item: any) => item.name === 'layout')

//   // 开始进度条
//   loadingBarShow.value = true

//   // 页面刷新
//   if (isInitRoutes && to.path !== '/login') {
//     // 如果未获得菜单列表,则跳转到登录页
//     if (!menuList || !menuList.length) {
//       next({ path: '/login', replace: true })
//       return
//     }
//     // 已获得菜单列表,则将菜单列表添加到路由中
//     setMenuList()

//     if (!fistMenu) {
//       next({ path: '/login', replace: true })
//       return
//     }

//     // 重定向到首页
//     if (to.path === '/') {
//       next({ path: fistMenu, replace: true })
//       return
//     }

//     // 重新跳转到目标路由
//     next({ ...to, replace: true })
//     return
//   }
  // 设置页面标题
  document.title = to.meta.title as string
  next()
})

router.afterEach(() => {
  const { loadingBarShow } = storeToRefs(useLoadingBarStore())
  // 结束进度条
  setTimeout(() => {
    loadingBarShow.value = false
  }, 100)
})

export default router
